//
//  GImageField.swift
//  housingResources
//
//  Created by zhu xietong on 2017/7/22.
//  Copyright © 2017年 节操君. All rights reserved.
//

import Foundation
import AVKit
import AVFoundation
import Eelay
import soapp
import TZImagePickerController

class UploadImageCell: RuleCell {
    let imgV = UIImageView()
    let bar = UIView()
    let lable = UILabel()

    override func addLayoutRules() {
        contentView.eelay = [
            [imgV,[ee.T.L.B.R,[1,1,-1,-1]]],
        ]
        
        let deleteBt = UIButton()
        eelay = [
            [bar,"20",[ee.L.B.R,[1,-1,-1]]],
            [deleteBt,[ee.B.R],"40",40]
        ]
        
        let tashBt = UIButton()
        bar.bsui.background(hex: "#0006")
        bar.eelay = [
            [lable,[ee.L.Y,[2,0]],[tashBt,ee.L,ee.R,-2]],
            [tashBt,[ee.Y.R,[0,6]],"33",33],
        ]
        tashBt.contentEdgeInsets = [8,8,8,8]
        tashBt.setImage(UIImage(named: "f_tash_white"), for: .normal)
        lable.ui.center.font10.cl_fff.text("待上传")

        bar.isUserInteractionEnabled = false
        clipsToBounds = true
        tashBt.addTarget(self, action: #selector(deleteAction), for: .touchUpInside)
        deleteBt.addTarget(self, action: #selector(deleteAction), for: .touchUpInside)

    }
    
    
    
    @objc func deleteAction() {
        self.delegate?.active(onwer: self, actionID: "delete_item", data: mo.model)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    
    override func mo_model_reload() {
        
        imgV.image = nil
        imgV.bsui.set(radius: 0, width: 0.5, color: UIColor(shex:"#ccc"))
        bar.isUserInteractionEnabled = true
        bar.alpha = 1.0
        if mo.model["isAdd","NO"] == "YES"
        {
            imgV.image = UIImage(named: "form-add")
            imgV.bsui.set(radius: 0, width: 0.5, color: .clear)
            bar.isUserInteractionEnabled = false
            bar.alpha = 0.0
            return
        }
        if let img = mo.model.object(forKey: "img") as? UIImage{
            lable.text = "待上传".loc
            imgV.image = img
            return
        }
        lable.text = "已上传".loc
        imgV.img_url = mo.model["__url",""]
        
    }
    
}

public class GImageField: FieldView
{
    let imgsView = RuleView<UploadImageCell>()
    
    var addTag = [
        "isAdd":"YES",
        "img":"",
    ].mutable_dictionary
    var max_count = 1
    
    var valueChange:(String) ->Void = {_ in}
    
    override public func addLayoutRules() {
        
        self.eelay = [
            [imgsView,[ee.T.L.B.R]],
        ]
//        imgsView.delegate = self
//        imgsView.actionDelegate = self
        imgsView.space = (8,8)
        imgsView.limit_width = Swidth - 40
        imgsView.que_num =  (Swidth > 321.0) ? 5 : 4
        
        imgsView.padding = [0,0,0,0]
//        imgsView.item_scale = 450.0/600.0
        imgsView.item_scale = 1
        weak var wself = self
        imgsView.touchAction = { cell,ID,model in
            
            guard let ws = wself else {
                return
            }
            
            
            if model["isAdd","NO"] == "YES"
            {
                wself?.toSelectImages()
            }
            if ID == "delete_item"
            {
                let list = ws.images
                //            let index = Int(model["index","0"]) ?? 0
                list.remove(model)
                if list.count < ws.max_count
                {
                    list.add(ws.addTag)
                }
                
                ws.mo.model[FK.options] = list
                ws.imgsView.mo.model = ws.mo.model
                ws.save(ws.get_string_value())
                ws.valueChange("deleteImage")
            }
        }
    }
//
//    func touch(ruleView: UIView, cell: RuleCell, actionID:String, model: NSMutableDictionary) {
//        if model["isAdd","NO"] == "YES"
//        {
//            toSelectImages()
//        }
//    }
//
//    func touch(ower: Any, actionID: String, model: NSMutableDictionary) {
//        if actionID == "delete_item"
//        {
//            let list = self.images
////            let index = Int(model["index","0"]) ?? 0
//            list.remove(model)
//            if list.count < max_count
//            {
//                list.add(addTag)
//            }
//
//
//            self.mo.model[FK.options] = list
//            imgsView.mo.model = self.mo.model
//            self.valueChange("addImages")
//        }
//
//    }
    
    var images:NSMutableArray{
        get{
            let vs = mo.model[FK.value,"[]"].JsonArray ?? NSMutableArray()
            let options = DataNode.path(node: "options", mo.model, value: vs)
            
            weak var wself = self
            
            let list = NSMutableArray()
            options.list { (dict:NSMutableDictionary, i) in
                if dict["isAdd","NO"] == "YES"
                {
                    wself?.addTag = dict
                }
                else{
                    list.add(dict)
                }
            }
            return list
        }
    }
    
    override public func mo_model_reload() {
        
        max_count = Int(mo.model[FK.max_mum,"1"]) ?? 1
        let list = self.images
        if list.count < max_count
        {
            list.add(addTag)
        }
        mo.model[FK.options] = list
        imgsView.mo.model = mo.model
    }
    
    
    override public func get_string_value() -> String {
        let imgs = self.images

        var list = [[String:Any]]()
        imgs.list { (obj:NSMutableDictionary, i) in
            list.append(
                [
                    "filename":obj["filename",""],
                    "path":obj["path",""],
                    "ftype":obj["ftype",""],
                    "__url":obj["__url",""]
                ])
        }

        return list.rawJson ?? "[]"
    }
  
}



extension GImageField:TZImagePickerControllerDelegate{
    
    func toSelectImages() {
        
        
        let max = max_count - self.images.count
        let ctr = TZImagePickerController(maxImagesCount: max, columnNumber: 3, delegate: self, pushPhotoPickerVc: true)
        ctr?.allowTakePicture = true
        ctr?.title = mo.model[FK.placeholder,"选择图片".loc]
        ctr?.showPhotoCannotSelectLayer = true
        
        
//
        ctr?.navigationBar.backIndicatorImage = nil
        ctr?.navigationBar.backItem?.backBarButtonItem?.setTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: 0), for: .default)
        ctr?.navigationBar.backIndicatorTransitionMaskImage = UIImage.image(.clear, size: [0.1,0.1])
//        ctr?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor(shex:"#fff"),NSAttributedString.Key.font:UIFont.systemFont(ofSize: 16)]
//        ctr?.navigationBar.tintColor = .white
//
        
        let style = EeTopStyle.default
        //        switch style.navBarBgStyle {
        //        case .color(let color):
        //            ctr?.naviBgColor = color
        //
        //        default:
        //            ctr?.naviBgColor = UIColor.white
        //
        //        }
  
        
//        ctr?.navigationBar.tintColor = .color(light: "#262626", dark: "#f1f1f1")
//        ctr?.statusBarStyle = style.statusBarStyle
     
        switch mo_theme.mode {
        case .dark:
            ctr?.naviBgColor = .init(white: 0.1, alpha: 1)
            ctr?.navigationBar.tintColor = .white
            ctr?.naviTitleColor = .white
            ctr?.barItemTextColor = .white

        default:
            ctr?.naviBgColor = .init(white: 0.1, alpha: 1)
            ctr?.navigationBar.tintColor = .gray
            ctr?.naviTitleColor = .gray
            ctr?.barItemTextColor = .gray
 
        }

       
        weak var wself = self
        ctr?.didFinishPickingPhotosHandle = {
            (imgs:[UIImage]?,asset:[Any]?,isSelectOriginalPhoto:Bool?) in
            
            if let list = imgs{
                wself?.addImages(imgs: list)
            }
            
        }
        
        
        mo.controller?.present(ctr!, animated: true
            , completion: nil)
    }
    
    func addImages(imgs:[UIImage]) {
        
        let list = self.images
        var i = list.count
        for img in imgs
        {
            
            let smallPng = img.commpress(maxSize: 800)
            print("________|\(smallPng)")
            let url = smallPng.saveToTemp().path
            print("_____ddd___|\(url)")
            let img = ["img":smallPng,"path":url].mutable_dictionary
            img["index"] = "\(i)"
            list.add(img)
            i = i + 1
            
        }
        
        //        uploadFiles(files: list)
        if list.count < max_count
        {
            list.add(addTag)
        }
        
        mo.model[FK.options] = list
        imgsView.mo.model = mo.model
        self.save(self.get_string_value())
        self.valueChange("addImages")
    }
    
   
    

    
}
